import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:1,
    isRepetition:false,
    success:false,
    todoList:JSON.parse(localStorage.getItem("todo")) || []
  },
  //只支持同步操作
  mutations: {
    PLUS_ACTION(state){
      state.count++
    },
    ADD_TODO(state,todoItem){
      var flag = false;
      state.todoList.forEach(element => {
        if(element.todoText === todoItem.todoText){
          flag = true;
        }
      });

      if(flag){
        state.isRepetition = true;
      }else{
        state.success  = true;
        state.todoList.push(todoItem);
      }

      //保存数据
      localStorage.setItem("todo",JSON.stringify(state.todoList))
    },
    CHANGE_STATUS(state){
      state.isRepetition = false;
      state.success = false;
    },
    CHANFGE_TODO_STATUS(state,todo){
      var todoItem = state.todoList.find((element)=>{
        return element.todoText  === todo.todoText;
      });

      if(todoItem){
        todoItem.status = todo.status;
      }

      //保存数据
      localStorage.setItem("todo",JSON.stringify(state.todoList))
    },
    CLEAR_DOEN(state){
      var temp = [];
      state.todoList.forEach(element => {
        if(!element.status){
          temp.push(element);
        }
      });
      state.todoList = temp;
      //保存数据
      localStorage.setItem("todo",JSON.stringify(state.todoList))
    },
    DELETEE_TODO(state,todo){
      var index = state.todoList.findIndex(element => {
        return element.todoText === todo.todoText;
      });

      if(index !== -1){
        state.todoList.splice(index,1);
      }
      //保存数据
      localStorage.setItem("todo",JSON.stringify(state.todoList))
    }
  },
  getters:{
    allTodoItems:function(state){
      return state.todoList;
    },
    doneTodoItems:function(state) {
      var temp  = [];
      // console.log(state.todoList)
      state.todoList.forEach(element => {
        if(element.status){
          // console.log("11111")
          temp.push(element);
        }
      })
      // console.log(temp)
      return temp;
    },
    penddingTodoItems:function(state) {
      var temp  = [];
      state.todoList.forEach(element => {
        if(!element.status){
          temp.push(element);
        }
      })
      return temp;
    }
  },
  actions: {
    PLUS_ACTION(context){
      setTimeout(() => {
        context.commit("PLUS_ACTION")
      }, 3000);
    }
  },
  modules: {
  }
})
